package com.wu.store.controller;

import com.wu.store.annotation.AdminUser;
import com.wu.store.annotation.CurrentUser;
import com.wu.store.common.util.MessageEntity;
import com.wu.store.dao.CategoryDao;
import com.wu.store.entity.Category;
import com.wu.store.entity.PageResult;
import com.wu.store.entity.Pagination;
import com.wu.store.entity.User;
import com.wu.store.service.CategoryService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {
	@Autowired
	private CategoryService categoryService;

	@RequestMapping("/list")
	public MessageEntity getList(String keyword) {
		List<Category> categories = categoryService.getCategories(keyword);
		return new MessageEntity.Builder().success(true).data(categories).create();
	}

	@RequestMapping("/isNameValid")
	public MessageEntity isNameValid(Category category) throws Exception {
		return new MessageEntity.Builder().success(categoryService.isNameValid(category)).create();
	}

	@RequestMapping("/save")
	public MessageEntity save(@AdminUser boolean isAdmin, Category category) throws Exception {
		if (category.getId() != null) {
			category.setUpdateTime(new Date());
		} else {
			category.setCreateTime(new Date());
		}
		if (StringUtils.isEmpty(category.getName())) {
			throw new Exception("请输入类别名称");
		}
		boolean flag = categoryService.isNameValid(category);
		categoryService.save(category);
		return new MessageEntity.Builder().success(flag).message("操作成功").create();
	}

	@RequestMapping("/delete")
	public MessageEntity delete(@CurrentUser User user, Integer id) throws Exception {
		if (user.getRole() != 1) {
			throw new Exception("无权进行该操作");
		}
		if (id == null) {
			throw new Exception("id必需");
		}
		boolean flag = categoryService.deleteCategoryById(id);
		String message;
		if (flag) {
			message = "删除成功";
		} else {
			message = "删除失败";
		}
		return new MessageEntity.Builder().success(flag).message(message).create();
	}

}
